package com.example.verse_systems;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;

import android.hardware.Camera;
import android.net.Uri;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.Manifest;
import android.provider.ContactsContract;

import android.provider.MediaStore;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;



public class MainActivity extends FlutterActivity {


    private MethodChannel.Result results;

    private static final int PERMISSION_REQUEST_CODE = 0;
    private static final int OPEN_GALLERY_REQUEST_CODE = 2;


    // 设置状态栏沉浸式透明（修改flutter状态栏黑色半透明为全透明）
    @Override
    protected void onCreate(@Nullable android.os.Bundle  savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTranslucentStatus(this.getActivity());
    }


 /*    //TODO 处理权限结果回调
    @Override
    public void onRequestPermissionsResult(int requestCode,   String[] permissions,   int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i("处理权限结果回调", String.valueOf(requestCode));
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.i("TAG", "onRequestPermissionsResult granted");
            results.success(true);
        } else {
            Log.i("TAG", "onRequestPermissionsResult denied");
            // TODO 用户拒绝权限申请，则弹出警示框
            results.success(false);
        }
    }
*/



    @SuppressLint("Range")
    private String[] getPhoneContacts(Uri uri){
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = this.getActivity().getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null&&cursor.moveToFirst()) {
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            contact[1]= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.i("contacts",contact[0]);
            Log.i("contactsUsername",contact[1]);
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }


    /**
     * 去掉手机号内除数字外的所有字符
     *
     * @param phoneNum 手机号
     * @return
     */
    private String formatPhoneNum(String phoneNum) {
        String regex = "(\\+86)|[^0-9]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNum);
        return matcher.replaceAll("");
    }



   // 自己写的相册回调base64慢,应该直接传递图片地址
    @Override
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(this.getClass().getName(), "Result:" + requestCode +resultCode);

        //选择通讯录联系人
        if (data != null&requestCode == PERMISSION_REQUEST_CODE) {

            Uri uri=data.getData();
            String[] contact= getPhoneContacts(uri);
            if (contact!=null){
                String name = contact[0];//姓名
                String phone =contact[1];//手机号
                phone = formatPhoneNum(phone);

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("phone", phone);
                resultMap.put("name", name);
                Log.e(this.getClass().getName(), "resultMap:" +resultMap);
                results.success(resultMap);
            }

        }


    }




    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor(), "open_native_camera");

        //设置监听
        methodChannel.setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall( @NotNull MethodCall call,  @NotNull MethodChannel.Result result) {
                        String lMethod = call.method;

                        switch (lMethod){
                            //打开相机
                            case "open_camera":
                                //检测权限
                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                                        != PackageManager.PERMISSION_GRANTED) {
                                    // 如果没有权限，则申请需要的权限
                                    ActivityCompat.requestPermissions(MainActivity.this,
                                            new String[]{
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                                    Manifest.permission.CAMERA}, 1009);
                                    result.success(false);
                                }else {
                                    // 已经申请了权限
                                    result.success(true);
                                }
                                break;
                            //打开人脸识别
                            case "open_face":{
//                                results = result;
//                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT);
//                                startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE);
                            }
                            break;
                            //打开通讯录
                            case "open_contact":{
                                results = result;
                                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                                intent.addCategory("android.intent.category.DEFAULT");
                                intent.setType("vnd.android.cursor.dir/phone_v2");
                                startActivityForResult(intent, PERMISSION_REQUEST_CODE);
                            }

                            break;
                            //打开相册
                            case "open_album":{
                                //检测权限
                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        != PackageManager.PERMISSION_GRANTED) {
                                    // 如果没有权限，则申请需要的权限
                                    ActivityCompat.requestPermissions(MainActivity.this,
                                            new String[]{
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                            }, 1008);
                                    result.success(false);
                                }else {
                                    // 已经申请了权限
                                    result.success(true);
                                }
                            }

                            break;

                            //申请通讯录权限
                            case "open_permission":
                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                                    Log.i("获取通讯录信息", "权限申请");
                                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_CONTACTS},1005);
                                    result.success(false);
                                }else {
                                    result.success(true);
                                }
                                break;

                            //获取通讯录信息
                            case "open_contact_address":{
                                DeviceTools deviceTools =  new  DeviceTools(MainActivity.this);
                                String jsonArray =  deviceTools.queryContacts();
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("jsonArray", jsonArray);
                                result.success(resultMap);
                            }
                            break;
                            //获取安装app信息
                            case "open_appInfo":{
                                String jsonArray = DeviceTools.getApplicationListNames(MainActivity.this);
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("jsonArray", jsonArray);
                                result.success(resultMap);
                            }
                            break;

                            //申请短信权限
                            case "open_permission_sms":{
                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
                                    Log.i("获取短信信息", "权限申请");
                                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_SMS},1006);
                                    result.success(false);
                                }else {
                                    result.success(true);
                                }
                              }

                                break;
                            //上传短信
                            case "open_smsInfo":{
                                DeviceTools deviceTools =  new  DeviceTools(MainActivity.this);
                                String jsonArray =  deviceTools.querySmsRecords();
                                Log.i("短信", jsonArray);
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("jsonArray", jsonArray);
                                result.success(resultMap);
                            }

                                break;
                            //申请通话记录权限
                            case "open_permission_call":
                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                                    Log.i("获取通话记录信息", "权限申请");
                                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_CALL_LOG},1007);
                                    result.success(false);
                                }else {
                                    result.success(true);
                                }

                            break;
                            //通话记录
                            case "open_callHistory":{
                                DeviceTools deviceTools =  new  DeviceTools(MainActivity.this);
                                String jsonArray =  deviceTools.queryCallRecords();
                                Log.i("通话记录", jsonArray);
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("jsonArray", jsonArray);
                                result.success(resultMap);
                            }
                            break;
                            //获取手机设备信息
                            case "open_deviceInfo":{

                                int height_pixels = DeviceTools.getDisplayMetrics(MainActivity.this).heightPixels;
                                int width_pixels = DeviceTools.getDisplayMetrics(MainActivity.this).widthPixels;
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("brand", DeviceTools.getBrand());
                                resultMap.put("device_name", DeviceTools.getProduct());
                                resultMap.put("model", DeviceTools.getModelName());
                                resultMap.put("sdk_version", DeviceTools.getDeviceSDK_INT());
                                resultMap.put("release", DeviceTools.getSystemVersion());
                                resultMap.put("serial_number", DeviceTools.getDeviceSerialNumber());
                                resultMap.put("last_boot_time", DeviceTools.getElapsedRealtime());
                                resultMap.put("network_operator_name", "");
                                resultMap.put("width_pixels", width_pixels);
                                resultMap.put("height_pixels", height_pixels);
                                resultMap.put("ram_total_size", DeviceTools.getRamTotalSize(MainActivity.this));
                                resultMap.put("ram_usable_size", DeviceTools.getFreeMem(MainActivity.this));
                                resultMap.put("internal_storage_usable", "");
                                resultMap.put("internal_storage_total", DeviceTools.getTotalMem());
                                resultMap.put("memory_card_size", DeviceTools.getSDAllSize());
                                resultMap.put("memory_card_size_use", DeviceTools.getSDFreeSize());
                                resultMap.put("is_charging", "0");
                                resultMap.put("battery_pct", DeviceTools.getBatteryPercent(MainActivity.this));
                                resultMap.put("latitude", "");
                                resultMap.put("longitude", "");
                                resultMap.put("country_name", "");
                                resultMap.put("admin_area", "");
                                resultMap.put("locality", "");
                                resultMap.put("sub_admin_area", "");
                                resultMap.put("feature_name", "");
                                resultMap.put("address", "");
                                resultMap.put("network_type", "");
                                resultMap.put("network_ip", "");
                                resultMap.put("network_mac", "");
                                resultMap.put("physical_size", "");
                                resultMap.put("device_uuid", DeviceTools.getIMEI());
                                result.success(resultMap);
                            }
                            break;

                            default:break;
                        }
                    }
                }
        );

        

    }







}
